package org.kkhweb.checkbook;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;

public class SimpleFiles {

	private String _errorMsg;
	private boolean _hasError;
	private String output;
	
	private FileOutputStream fos;
	private FileInputStream fis;
	private Context context;

	public SimpleFiles(Context context)
	{
		this.context = context;
		this.fis = null;
		this.fos = null;
		this._hasError = false;
		this._errorMsg = "";
	}
	
	public void readFile(String filename)
	{
		int ch;
	    StringBuffer strContent = new StringBuffer("");
		try {
			this.fis = this.context.openFileInput(filename);
			while((ch = this.fis.read()) != -1) {
				strContent.append((char)ch);
			}
			//this.fis.reset();
			this.fis.close();
			this.output = strContent.toString(); 
		} catch (FileNotFoundException e) {
			this._setErrorStatus(true);
			this._setErrorMsg(e.getMessage());
		} catch (IOException e) {
			this._setErrorStatus(true);
			this._setErrorMsg(e.getMessage());
		}
	}    

	public void saveFile(String filename, String contents)
	{
		try {
			this.fos = this.context.openFileOutput(filename, Context.MODE_PRIVATE);
			this.fos.write(contents.getBytes());
			this.fos.close();
			this._setErrorStatus(false);
		} catch (FileNotFoundException e) {
			this._setErrorStatus(true);
			this._setErrorMsg(e.getMessage());
		} catch (IOException e) {
			this._setErrorStatus(true);
			this._setErrorMsg(e.getMessage());
		}
	}	
	
	public String getOutput()
	{
		return this.output;
	}
	
	public boolean hasError()
	{
		return this._hasError;
	}

	public String getError()
	{
		return this._errorMsg;
	}
	
	// Private Methods
	private void _setErrorMsg(String msg)
	{
		this._errorMsg = msg;
	}

	private void _setErrorStatus(boolean status)
	{
		this._hasError = status;
	}

}